require('../js/global.js');
var http = require('http');
var url = require('url');
var exec = require('child_process').exec;
var Iconv = require('iconv').Iconv;
var ServerManager = require('../js/servers.js').ServerManager;

global.gOrderPath = "online/orders";
global.gUserHome = "";

global.gProcessName = 'profiler';
global.gServers = new ServerManager();
global.gStat = require('./stat/index.js');
global.gMysqlPool = require('./pool.js');
var logic = require('./logic');


main();

function main() {
    async.series([
        function (cb) {
            gServers.load({slave:true, native:true}, function(err) {
                cb(err);
            });
        },
        function(cb) {
            gMysqlPool.init("login", function(err) {
                cb(err);
            });
        },
        function (cb) {
            gStat.pool.init(function(err) {
                cb(err);
            });
        },
        function (cb) {
            gStat.pay.load(function(err) {
                cb(err);
            });
        },
        function(cb) {
            require('../js/util.js').getUserHome(function(home){
                gUserHome = home;
                cb(null);
            });
        }
    ], function(err, results) {
        if (err) {
            LOG(util.format('start %s failed: %j', gProcessName, err));
            process.exit(-1);
        }
        
        LOG(util.format('%s start', gProcessName));
        startWebServer({
            port: config.platform.gm.profiler.port,
            timeout: 1200*1000,
        });

        setInterval(function() {
            gServers.loadGame(function(err) {});
        }, 600*1000);

        setInterval(function() {
            gStat.pay.save();
        }, 1800*1000);

        process.on('SIGINT', function() {
            onProcessExit();
        });

        process.on('SIGTERM', function() {
            onProcessExit();
        });

        process.on('uncaughtException', function (err) {  
            LOG(err.stack);        
        });
    });
};


function onProcessExit() {
    LOG('process exit');
    var pidFile = util.format('%s.pid', gProcessName);
    LOG(util.format('%s shutdown', gProcessName));
    fs.existsSync(pidFile) && fs.unlinkSync(pidFile);
    process.exit();
}

function startWebServer(options) {
    var port = options.port;
    var timeout = options.timeout;

    var webServer = http.createServer(function(req, res) {
        var reqObj = url.parse(req.url, true);
        var query = reqObj.query || {};
        var path = reqObj.pathname.substring(1).split('/');

        if( req.method == 'POST' ) {
            req.connection.destroy();
            return;
        }
        
        req.on('end', function() {
            if (path.length != 2) {
                res.writeHead(404, {"Content-Type": "text/plain"});
                res.end(JSON.stringify({code:1, desc:'path invalid'}));
                return;
            }

            var modName = path[0];
            var actName = path[1];

            var module = logic[modName];
            if (!module) {
                res.writeHead(404, {"Content-Type": "text/plain"});
                res.end(JSON.stringify({code:1, desc:'mod invalid'}));
                return;
            }
            
            var handler = module[actName];
            if (!handler) {
                res.writeHead(404, {"Content-Type": "text/plain"});
                res.end(JSON.stringify({code:1, desc:'act invalid'}));
                return;
            }

            var resp = {code:0, desc:'', data:[]};
            handler(query, resp, function() {
                if (resp.plain) {
                    res.writeHead(200, common.defaultHeaders);
                    res.end(resp.data);
                } else {
                    res.writeHead(200, common.htmlHeaders);
                    res.end(JSON.stringify(resp));
                }
            });
        });

        req.resume();
    });
    
    webServer.listen(port);
    webServer.timeout = timeout;
}
